package com.eastmelon.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.MemoryCacheImageInputStream;

public class Base64Util {

	// base64字符串转化成图片
	public static String GenerateImageType(String imgStr) { // 对字节数组字符串进行Base64解码并生成图片
		if (imgStr == null) // 图像数据为空
			return "";
		try {
			// Base64解码
			byte[] b = Base64.decode(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			InputStream in = new ByteArrayInputStream(b); // 这里是你已经存在的输入流
			String type = CheckExcelFileTypeUtil.getFileType(in);

			return type;
		} catch (Exception e) {
			return null;
		}
	}

	public static Integer GenerateImageSize(String imgStr) {
		if (imgStr == null)
			return 0;
		try {
			byte[] b = Base64.decode(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			InputStream in = new ByteArrayInputStream(b);
			int size = in.available();
			return size;
		} catch (Exception e) {
			return null;
		}
	}

	public static byte[] getBytes(String imgStr) {
		if (imgStr == null)
			return null;
		byte[] b=null;
		try {
			b = Base64.decode(imgStr);
		} catch (Exception e) {
			return null;
		}
		return b;
	}

	public static final BufferedImage readMemoryImage(String imgStr)
			throws IOException {
		byte[] imgBytes=getBytes(imgStr);
		if (null == imgBytes || 0 == imgBytes.length)
			throw new NullPointerException(
					"the argument 'imgBytes' must not be null or empty");
		// 将字节数组转为InputStream，再转为MemoryCacheImageInputStream
		ImageInputStream imageInputstream = new MemoryCacheImageInputStream(
				new ByteArrayInputStream(imgBytes));
		// 获取所有能识别数据流格式的ImageReader对象
		Iterator<ImageReader> it = ImageIO.getImageReaders(imageInputstream);
		// 迭代器遍历尝试用ImageReader对象进行解码
		while (it.hasNext()) {
			ImageReader imageReader = it.next();
			// 设置解码器的输入流
			imageReader.setInput(imageInputstream, true, true);
			// 图像文件格式后缀
			// String suffix = imageReader.getFormatName().trim().toLowerCase();
			// 图像宽度
			// int width = imageReader.getWidth(0);
			// 图像高度
			// int height = imageReader.getHeight(0);
			try {
				// 解码成功返回BufferedImage对象
				// 0即为对第0张图像解码(gif格式会有多张图像),前面获取宽度高度的方法中的参数0也是同样的意思
				return imageReader.read(0, imageReader.getDefaultReadParam());
			} catch (Exception e) {
				imageReader.dispose();
				// 如果解码失败尝试用下一个ImageReader解码
			}
		}
		imageInputstream.close();
		// 没有能识别此数据的图像ImageReader对象，抛出异常
		throw new IOException("unsupported image format");
	}
}
